var logLineNumber = 0;
$(document).ready(function() {

    function addMessageToLog(message) {
        var logDiv = $('#log');
        var currentDateTime = new Date().toLocaleString();
        var dateTimeSpan = $('<span></span>').text('[' + currentDateTime + ']').addClass('date-time');
        var messageSpan = $('<span></span>').text(message).addClass('message-content');
        var p = $('<p></p>').append(dateTimeSpan).append(messageSpan);
        logDiv.append(p);
        var logLines = logDiv.find('p');
        if (logLines.length > 300) {
            logLines.first().remove();
        }
        logDiv.scrollTop(logDiv[0].scrollHeight);
    }

    var websocket = new WebSocket(websocketUrl);
    websocket.onopen = function(event) {
        console.log("WebSocket连接已打开。");
    };
    websocket.onmessage = function(event) {
        var message = event.data;
        addMessageToLog(message);
    };
    websocket.onclose = function(event) {
        console.log("WebSocket连接已关闭。");
    };
    websocket.onerror = function(event) {
        console.log("发生WebSocket错误：", event);
    };

    // 当页面即将卸载时，关闭WebSocket连接
    $(window).on('beforeunload', function() {
        if (websocket && websocket.readyState === WebSocket.OPEN) {
            websocket.close();
        }
    });
    // 发送消息的函数
    function sendMessage(message) {
        if (websocket.readyState === WebSocket.OPEN) {
            websocket.send(message);
        } else {
            console.error("WebSocket连接未打开。");
        }
    }

    $('#containerSelect').change(function() {
        // 取消上一个容器的订阅
        var previousContainerId = $(this).data('previous-container-id');
        if (previousContainerId) {
            var unsubscribeMessage = {
                containerId: previousContainerId,
                operation: 'UNSUBSCRIBE'
            };
            var jsonUnsubscribeMessage = JSON.stringify(unsubscribeMessage);
            sendMessage(jsonUnsubscribeMessage);
        }

        // 清空日志显示并更新选择的容器ID
        $('#log').empty();
        $(this).data('previous-container-id', $(this).val());
    });

    $('#startButton').click(function() {
        var selectedContainerId = $('#containerSelect').val();
        if (selectedContainerId) {
            var message = {
                containerId: selectedContainerId,
                operation: 'SUBSCRIBE'
            };
            var jsonMessage = JSON.stringify(message);
            sendMessage(jsonMessage);
        } else {
            alert('请选择一个容器！');
        }
    });

    $('#stopButton').click(function() {
        var selectedContainerId = $('#containerSelect').val();
        if (selectedContainerId) {
            var message = {
                containerId: selectedContainerId,
                operation: 'UNSUBSCRIBE'
            };
            var jsonMessage = JSON.stringify(message);
            sendMessage(jsonMessage);
        } else {
            alert('请选择一个容器！');
        }
    });

    // Ajax调用以获取容器列表并填充下拉框
    $.ajax({
        url: '/szb/docker/containers', // 后端提供的容器查询接口URL
        type: 'GET',
        success: function(containers) {
            containers.forEach(function(container) {
                $('#containerSelect').append($('<option></option>').val(container.id).html(container.names));
            });
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error fetching container list: ' + textStatus, errorThrown);
        }
    });
});